#include "ISNW_CtrlInterface.h"
#include "../../ISNW_Application.h"
using namespace ISNW;

ISNW_CtrlInterface::ISNW_CtrlInterface()
:m_parent(ISNW_NULL)
{
	m_pos = D3DXVECTOR3(0,0,0);
	m_rotate = D3DXVECTOR3(0,0,0);
	m_scale = D3DXVECTOR3(1,1,1);
}


ISNW_VOID ISNW_CtrlInterface::SetPos(ISNW_INT x,ISNW_INT y,ISNW_INT z)
{
	m_pos = D3DXVECTOR3(x,y,z);
}

ISNW_VOID ISNW_CtrlInterface::Translate(ISNW_INT x,ISNW_INT y,ISNW_INT z)
{
	m_pos.x += x;
	m_pos.y += y;
	m_pos.z += z;
}

D3DXVECTOR3 ISNW_CtrlInterface::Cvt2ScreenPos()
{
	D3DXVECTOR3 _pos = D3DXVECTOR3(0,0,0);
	if(m_parent){
		_pos = m_parent->Cvt2ScreenPos();
	}
	return (_pos + m_pos);
}

ISNW_VOID ISNW_CtrlInterface::SetRotate(float x,float y,float z)
{
	m_rotate = D3DXVECTOR3(x,y,z);
}

ISNW_VOID ISNW_CtrlInterface::Rotate(float x,float y,float z)
{
	m_rotate += D3DXVECTOR3(x,y,z);
}

D3DXVECTOR3 ISNW_CtrlInterface::Cvt2ScreenRotate()
{
	D3DXVECTOR3 _rotate = D3DXVECTOR3(0,0,0);
	if(m_parent){
		_rotate = m_parent->Cvt2ScreenRotate();
	}
	return (_rotate + m_rotate);
}

ISNW_VOID ISNW_CtrlInterface::SetScale(float x,float y,float z)
{
	m_scale = D3DXVECTOR3(x,y,z);
}

ISNW_VOID ISNW_CtrlInterface::Scale(float x,float y,float z)
{
	m_pos += D3DXVECTOR3(x,y,z);
}

D3DXVECTOR3 ISNW_CtrlInterface::Cvt2ScreenScale()
{
	D3DXVECTOR3 _scale = D3DXVECTOR3(1,1,1);
	if(m_parent){
		_scale = m_parent->Cvt2ScreenScale();
	}
	_scale.x *= m_scale.x;
	_scale.y *= m_scale.y;
	_scale.z *= m_scale.z;
	return _scale;
}

ISNW_VOID ISNW_CtrlInterface::SetTransform(D3DXMATRIX* ptransform)
{
	D3DXMatrixIdentity(ptransform);

	D3DXVECTOR3 pos = Cvt2ScreenPos();
	D3DXVECTOR3 _pos = D3DXVECTOR3(0,0,0);
	_pos.z = pos.z;
	_pos.x = (pos.x - g_pApp->Width()/2)*2.0f*_pos.z/g_pApp->Height();
	_pos.y = (g_pApp->Height()/2 - pos.y)*2.0f*_pos.z/g_pApp->Height();

	D3DXVECTOR3 _rotate = Cvt2ScreenRotate();
	D3DXVECTOR3 _scale = Cvt2ScreenScale();

	D3DXMATRIX translate;
	D3DXMatrixTranslation(&translate,_pos.x,_pos.y,_pos.z);

	D3DXMATRIX rotate;
	D3DXMATRIX rotateX;
	D3DXMATRIX rotateY;
	D3DXMATRIX rotateZ;
	D3DXMatrixRotationX(&rotateX,Angle2Radian(_rotate.x));
	D3DXMatrixRotationY(&rotateY,Angle2Radian(_rotate.y));
	D3DXMatrixRotationZ(&rotateZ,Angle2Radian(_rotate.z));
	D3DXMatrixMultiply(&rotate,&rotateX,&rotateY);
	D3DXMatrixMultiply(&rotate,&rotate,&rotateZ);

	D3DXMATRIX scale;
	D3DXMatrixScaling(&scale,_scale.x,_scale.y,_scale.z);

	D3DXMatrixMultiply(ptransform,&scale,&rotate);
	D3DXMatrixMultiply(ptransform,ptransform,&translate);
}